<script setup>
import {Panel, useVueFlow} from '@vue-flow/core'
const flowKey = 'vue-flow--save-restore'

const {nodes, addNodes, dimensions, toObject, fromObject} = useVueFlow()

function onSave() {
	localStorage.setItem(flowKey, JSON.stringify(toObject()))
}

function onRestore() {
	const flow = JSON.parse(localStorage.getItem(flowKey))

	if (flow) {
		fromObject(flow)
	}
}

function onAdd() {
	const id = nodes.value.length + 1

	const newNode = {
		id: `random_node-${id}`,
		label: `Node ${id}`,
		position: {x: Math.random() * dimensions.value.width, y: Math.random() * dimensions.value.height},
	}

	addNodes([newNode])
}
</script>

<template>
	<Panel position="top-right">
		<div class="buttons flex gap-1">
			<n-button size="small" title="save graph" @click="onSave">
				保存
			</n-button>
			<n-button size="small" title="restore graph" @click="onRestore">
				恢复
			</n-button>
			<n-button size="small" title="add random node" @click="onAdd">
				添加
			</n-button>
		</div>
	</Panel>
</template>
